#!/usr/bin/env python

import re
import os
import urllib2

from urllib2 import urlopen


def main():
    exp = re.compile('/gallery/detail/(\d+).+?/thumbs_viewAll/tn_(.+?)"')
    for i in range(153, 500):
        url = 'http://logopond.com/all/?page=%d' % (i,)
        print url
        text = urlopen(url).read()
        images = re.findall(exp, text)
        print '%d images found\n' % (len(images),)
        for x in images:
            imgurl = 'http://logopond.com/logos/%s' % (urllib2.quote(x[1]),)
            print imgurl
            destname = '_'.join(x)
            if (os.path.exists(destname)):
                print '# the file "%s" exists, skipping' % (destname,)
                continue
            try:
                img = urlopen(imgurl).read()
            except urllib2.HTTPError:
                print '# HTTP error, run away!'
                continue
            try:
                dest = open(destname, 'wb')
            except:
                print '# failed to create the file "%s", skipping' % (destname,)
                continue
            dest.write(img)
            dest.close()
            print '# done, "%s" saved' % (destname,)


if __name__ == '__main__':
    main()
